<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\home\controller;

use think\Db;
use think\Validate;
use EasyWeChat\Factory;
use cmf\controller\RestBaseController;
use wechatvi\WxCrypt;
use think\Config;
use think\Cache;

class IndexController extends RestBaseController
{

    public $Token;
    public $UserId;
    public function __construct(){
        $token =  input('token') ? input('token') : $_SERVER['HTTP_TOKEN'];
        if(!$token){
            $this->error('请先登陆！');
        }
        $session = Db::table('a_user')->where(['session'=>$token])->value('session');
        if(!$session){
            echo json_encode(array('code'=>90001,'msg'=>'token已过期'));die;
        }
        $this->Token = $token;
        $this->UserId = substr($this->Token,12);
    }

    // api 首页
    public function index()
    {
        if(!input('biz_id')){
            $this->error('缺少小程序ID');
        }
        $appId = Config::get('appId');
        //获取access_token
        $access_token = getAuthorizerAccessToken($this->UserId);
        //4.获取预授权码pre_auth_code
        $authCodeApiUrl = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token='.$access_token;
        $param['component_appid'] = $appId;
        $param = json_encode($param);
        $authCodeData = post($authCodeApiUrl,$param);
        $authCodeData = json_decode($authCodeData,true);
        if(isset($authCodeData['errcode'])){
            $this->error('请求次数过多！');    
        }
        $authExpires = (string)$authCodeData['expires_in']; //有效时间  后续投入使用
        $authCode = $authCodeData['pre_auth_code']; //授权令牌
        //5.获取授权信息 组装授权域名
        $callback = (string) 'http://sell.wengcong.cn/?biz_id='.input('biz_id').'#/mp-manage/version'; //回调地址
        $jumpURL =  'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.$appId.'&pre_auth_code='.$authCode.'&redirect_uri='.$callback;
        $this->success('请求成功！',$jumpURL);
    }

    /**
     * [authorization_code 扫码确认授权获取授权码 回调地址]
     * @date   2018-06-03
     * @author 奇点
     * @return [type]     [description]
     */
    public function authorization_code(){
        if(!input('auth_code')){
            return $this->error('缺少auth_code');
        }else{
            //更新表
            //1.获取 componentAccessToken 
            $componentAccessToken = getAuthorizerAccessToken($this->UserId);
            $authCodeApiUrl = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token='.(string) $componentAccessToken;
            $authCode = (string)input('auth_code'); //授权码
            $expiresIn = (string)input('expires_in'); //有效期（s）
            $param['component_appid'] = Config::get('appId');
            $param['authorization_code'] = $authCode;
            $param = json_encode($param);
            $ref_tock = post($authCodeApiUrl,$param);
            $authorizer_refresh_token = json_decode($ref_tock,true);
            if(isset($authorizer_refresh_token['errcode'])){
                return $this->error('access_token:过期');
            }
            $appid = $authorizer_refresh_token['authorization_info']['authorizer_appid'];//
            $refresh_tokeen = $authorizer_refresh_token['authorization_info']['authorizer_refresh_token'];//令牌

            //获取小程序的详细信息
            $appinfo = $this->getAppDetails($componentAccessToken,Config::get('appId'),$appid);
            //把当前的这个小程序给清空
            
            if(Db::table('minipro_copy')->where(['appid'=>$appid])->count() > 0){
                //存在就清空其他绑定的
                Db::table('minipro_copy')->where(['appid'=>$appid])->where('biz_id','neq',input('biz_id'))->update([
                    'appid' => '',
                    'biz_username'=>'',
                    // 'appkey'=> '',
                    'refresh_token'=>'',
                    'status'=>1,
                    'app_name'=>'',
                    'datainfo'=>'',
                    'img_log'=>'',
                ]);
            }
            $rq = Db::table('minipro_copy')->where(['biz_id'=>input('biz_id')])->update([
                'appid'=>$appid,//小程序ID
                'biz_username'=>$appinfo['authorizer_info']['user_name'],
                'refresh_token'=>$refresh_tokeen,//令牌凭证 y
                'app_name'=>$appinfo['authorizer_info']['nick_name'],
                'img_log'=>$appinfo['authorizer_info']['head_img'],
                'datainfo'=>$appinfo['authorizer_info']['signature'],
                'img_log'=>$appinfo['authorizer_info']['head_img'],
                'qrcode_url'=>$appinfo['authorizer_info']['qrcode_url'],
                'status'=>2,
            ]);
            Cache::set('authorizer_access_token_'.input('biz_id'),$authorizer_refresh_token['authorization_info']['authorizer_access_token'],7200);
            if($rq){
                $this->commit(input('biz_id'));//提交小程序代码
                $this->setModifyDomain($authorizer_refresh_token['authorization_info']['authorizer_access_token']);
                $this->success('授权成功！');
            }
            $this->error('你已经授权绑定过了!');
        }
    }

    /**
     * [getAppDetails 获取小程序详情]
     * @return [type] [description]
     */
    public function getAppDetails($access_token='',$component_appid='',$authorizer_appid=''){
        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token='.$access_token;
        $data['component_appid'] = (string)$component_appid;
        $data['authorizer_appid'] = (string)$authorizer_appid;
        $param = json_encode($data);
        $rest = post($url,$param);
        $rest_list = json_decode($rest,true);
        return $rest_list;
    }
    /**
     * 1、为授权的小程序帐号上传小程序代码
     */
    public function commit($biz_id=140){
        if(!$biz_id){
            $this->error('缺少小程序ID');
        };
        //biz_id=140&auth_code=queryauthcode@@@lLNlRkKQI-TKRma6ondeZzyVuRWjP7IpDDC8mieUAWzcb-xcaDwTtXw5csDirdUW43AFdOM0pPJbKOUOYbmjSQ&expires_in=3600
        $ratkappid = authorizerAccessToken($this->UserId,$biz_id);
        $json = [
            'extEnable'=>false,
            'extAppid'=>$ratkappid['appid'],
            'ext'=>[
                "appid"=>$ratkappid['appid']
            ],
            // 'pages'=>['pages/index/index','pages/logs/index'],
            'window'=> ['navigationBarTitleText'=>'Demo'],
            // 'tabBar'=> [
            //     'list'=>[
            //         ['pagePath'=>'pages/index/index','text'=>'首页'],
            //         ['pagePath'=>'pages/logs/logs','text'=>'日志'],
            //     ],
            // ],
            'networkTimeout'=>['request'=>10000,'downloadFile'=>10000],
            'debug'=>true
        ];
        $user_version = '1.0';
        $user_desc = '版本说明';
        $xtid = $this->getxcxTplateid($biz_id);
        $url = 'https://api.weixin.qq.com/wxa/commit?access_token='.$ratkappid['authorizer_access_token'];
        $data['template_id'] = (string)$xtid;
        $data['ext_json'] = json_encode($json);
        $data['user_version'] = $user_version;
        $data['user_desc'] = $user_desc;
        $param = json_encode($data);
        $rest = post($url,$param);
        $rest_list = json_decode($rest,true);
        if(!isset($rest_list['errcode'])){
            $this->error('请将所有权限授予公众平台!');
        }
        Db::table('version_desc')->insert([
            'biz_id' => $biz_id,
            'user_version'=> $user_version,
            'ext_json'=>json_encode($json),
            'user_desc'=>$user_desc
        ]);
        return $rest_list;
    }

    /**
     * [getxcxTplateid 获取小程序ID]
     * @param  [type] $biz_id [description]
     * @return [type]         [description]
     */
    public function getxcxTplateid($biz_id){
        if(!$biz_id){
            $this->error('缺少小程序ID');
        }
        $xtid = Db::prefix_close()->table('minipro_copy')
            ->alias('a')
            ->join('minipro_template b','b.template_id=a.template_id')
            ->where(['a.biz_id'=>$biz_id])
            ->value('b.wxtemplate_id');
        return $xtid;
    }

    /**
     * [getVersionDesc 获取小程序版本信息]
     * @return [type] [description]
     */
    public function getVersionDesc(){
        if(!input('biz_id')){
            $this->error('缺少小程序ID');
        }
        $versionDesc=Db::table('version_desc')->where(['biz_id'=>input('biz_id')])->select();
        if($versionDesc){
            $this->success('请求成功！',$versionDesc);
        }
        $this->error('暂无版本信息');
    }

    /**
     * [getXcxQrcode 获取小程序体验二维码]
     * @return [type] [description]
     */
    public function getXcxQrcode(){
        if(!input('biz_id')){
            $this->error('缺少小程序ID');
        }
        $access_token  = authorizerAccessToken($this->UserId,input('biz_id'));
        if(!$access_token){
            $this->error('你还未绑定授权小程序！');
        }
        $url = 'https://api.weixin.qq.com/wxa/get_qrcode?access_token='.$access_token['authorizer_access_token'];
        $getXcxQrcode = get($url);
        file_put_contents('../../public/upload/xcxqrcode/qrcode'.input('biz_id').'.png',$getXcxQrcode);
        $this->success('返回成功!',Config::get('weburl').'/upload/xcxqrcode/qrcode'.input('biz_id').'.png');
    }


    /**
     * [getXcxMemberauth 获取小程序体验者列表]
     * @return [type] [description]
     */
    public function getXcxMemberauth(){
        if(!input('biz_id')){
            $this->error('缺少小程序ID');
        }
        $Mberauthlist = Db::table('experiencer')->where(['biz_id'=>input('biz_id')])->select();
        if($Mberauthlist){
            $this->success('请求成功！',$Mberauthlist);
        }
        $this->success('暂无数据',array());
    }

    /**
     * [MberauthAdd 新增小程序体验者]hjc66_88
     */
    public function MberauthAdd(){
        if(!input('biz_id')){
            $this->error('缺少小程序ID!');
        }
        if(!input('wechatname')){
            $this->error('请添加体验者微信号!');
        }
        $access_token = authorizerAccessToken($this->UserId,input('biz_id'));
        $url = 'https://api.weixin.qq.com/wxa/bind_tester?access_token='.$access_token['authorizer_access_token'];
        $data['wechatid'] = input('wechatname');
        $param = json_encode($data);
        $pushpram = post($url,$param);
        $MberauthAdd = json_decode($pushpram,true);
        if($MberauthAdd['errmsg'] == 'ok'){
            Db::table('experiencer')->insert([
                'biz_id'=>input('biz_id'),
                'userstr'=>$MberauthAdd['userstr'],
                'wechatname'=> input('wechatname')
            ]);
            $this->success('添加成功!');
        }
        if($MberauthAdd['errcode'] == 85004){
            $this->error('该微信号已经是体验者');
        }
        $this->error('微信号不存在!');
    }

    /**
     * [mberauthDle 删除体验者微信号]
     * @return [type] [description]
     */
    public function mberauthDle(){
        if(!input('biz_id')){
            $this->error('缺少小程序ID!');
        }
        if(!input('wechatname')){
            $this->error('缺少体验者微信号!');
        }
        $access_token = authorizerAccessToken($this->UserId,input('biz_id'));
        $url = 'https://api.weixin.qq.com/wxa/unbind_tester?access_token='.$access_token;
        $data['wechatid'] = input('wechatname');
        $param = json_encode($data);
        $pushpram = post($url,$param);
        $unbind_tester = json_decode($pushpram,true);
        if($MberauthAdd['errcode'] == 85004){
            $this->error('该微信号不是体验者!');
        }
        $this->success('解除成功!');
    }

    /**
     * [setModifyDomain 设置小程序域名]
     */
    public function setModifyDomain($authorizer_access_token){
        $url = 'https://api.weixin.qq.com/wxa/modify_domain?access_token='.$authorizer_access_token;
        $data['action'] = '';
        $data['requestdomain'] = ['https://api.wengcong.com'];
        $data['wsrequestdomain'] = ['https://api.wengcong.com'];
        $data['uploaddomain'] = ['https://api.wengcong.com'];
        $data['downloaddomain'] = ['https://api.wengcong.com'];
        $param = json_encode($data);
        $pushpram = post($url,$param);
        $setModifyDomain = json_decode($pushpram,true);
        return true;
    }
}
